package com.atcd.jdies.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/abTest")
public class redisLockTest {

    @Autowired
    private RedisTemplate redisTemplate;


    //分布式锁处理：redis
    @GetMapping("/testLock")
    public void testLock(){
        //防止误删别人的锁，加上一个uuid
        String uuid = UUID.randomUUID().toString();
        //1获取锁，setIfAbsent相当于setne                                                //最多5秒抢占锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);//还是要设置时间，防止抢占了锁，不释放的情况
        System.out.println(lock);
        //获取锁成功、查询num的值
        if(lock){
            Object value = redisTemplate.opsForValue().get("num");
            //判断num为空return
            if(StringUtils.isEmpty(value)){
                return ;
            }
              redisTemplate.opsForValue().increment("num",1);
            if(uuid.equals(redisTemplate.opsForValue().get("lock"))) {//前后的操作的id是否一样，才会释放锁
                //释放锁，del
                redisTemplate.delete("lock");
            }

        }else{
            //3获取锁失败、每隔0.1秒再获取
            try {
                Thread.sleep(100);
                testLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
